package com.fg.pro.trade.utils;

import cn.hutool.core.util.StrUtil;
import com.fg.pro.model.trade.dto.GmTokenDto;
import com.fg.pro.trade.config.GmTokenConfig;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.fg.pro.trade.constant.RedissonConst.*;

@Component
public class GmTokenUtils {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    GmTokenConfig gmTokenConfig;

    @Autowired
    GmHttpUtils gmHttpUtils;

    /**
     * 获取token
     * @return token
     * @throws InterruptedException
     */
    public String token() throws InterruptedException {
        String token = stringRedisTemplate.opsForValue().get(REDIS_CACHED_GM_TOKEN);
        if(StrUtil.isNotBlank(token)){
            return token;
        }
        RLock lock = redissonClient.getLock(REDIS_LOCK_GM_TOKEN);
        try {
            boolean tryLock = lock.tryLock(1, TimeUnit.SECONDS);
            if(!tryLock){
                return token();
            }
            token = stringRedisTemplate.opsForValue().get(REDIS_CACHED_GM_TOKEN);
            if(StrUtil.isNotBlank(token)){
                return token;
            }
            GmTokenDto.GmTokenRequest gmTokenRequest = new GmTokenDto().new GmTokenRequest(gmTokenConfig.app_id, gmTokenConfig.app_secret);
            GmTokenDto.GmTokenReponse gmTokenReponse = gmHttpUtils.httpPost(gmTokenConfig.app_url, gmTokenRequest, GmTokenDto.GmTokenReponse.class);
            token = gmTokenReponse.getToken();
            stringRedisTemplate.opsForValue().set(REDIS_CACHED_GM_TOKEN, token,6, TimeUnit.HOURS);
            return token;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 手动刷新token，在获取
     * @return token
     * @throws InterruptedException
     */
    public String refreshToken() throws InterruptedException {
        stringRedisTemplate.delete(REDIS_CACHED_GM_TOKEN);
        String token = token();
        return token;
    }


}
